﻿import React, {useEffect, useState} from 'react';
import {
    Link, useLocation,
    useNavigation
} from "react-router-dom";
import { Layout,Image,Typography,Button,Avatar } from "antd";
import Logo  from "../../images/instaverse.png";
import { useDispatch } from "react-redux";
import { LOGOUT } from "../../constants/actionTypes";
import decode from "jwt-decode";


import styles from "./styles";


const { Title } = Typography;
const { Header } = Layout;

export default function AppBar(){
    const dispatch = useDispatch();
    const navigate = useNavigation();
    const location = useLocation();

    const [user,setUser] = useState(JSON.parse(localStorage.getItem("profile")));

    useEffect(() => {
        const token = user?.token;
        if(token){
            const decodedToken = decode(token);
            if(decodedToken.exp * 1000 < new Date().getTime()) logout();
        }
        setUser(JSON.parse(localStorage.getItem("profile")));
    }, [location]);

    const logout = () =>{
        dispatch({ type: LOGOUT});
        navigate("/authform");
        setUser(null);
    }


    return(
        <Header style={styles.header}>
            <Link to={"/"}>
                <div style={styles.homeLink}>
                    <Image style={styles.image} width={"45"} preview={false} src={ Logo }/>
                    &nbsp;
                    <Title style={styles.title}>Instaverse</Title>
                </div>
            </Link>
            {!user ? (
                <Link to={"/authform"}>
                    <Button htmlType={"button"} style={styles.login}>
                        Log In
                    </Button>
                </Link>
            ):(
                <div style={styles.userInfo}>
                    <Avatar style={styles.avatar} alt={"username"} size={"large"}>
                        U
                    </Avatar>
                    <Title style={styles.title} level={4}>
                        John Doe
                    </Title>
                    <Button htmlType={"button"}>
                        Log Out
                    </Button>
                </div>
            )}
        </Header>
    )
}